package com.aaa.gs.filter;

import com.aaa.common.util.Result;
import com.aaa.common.util.ResultStatus;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * @ FileName: IllegalCharacterFilter
 * @ Description:
 * @ Author:  STB
 * @ CreateTime: 2025/9/2 0002 19:04
 * @ Version: 1.0.0
 */
@Component
@Log4j2
public class IllegalCharacterFilter implements GlobalFilter, Ordered {

    //把配置值注入当前属性
    @Value("${illegal_char}")
    private String illegalChar;  //illegalChar=sb,nnd,tmd,falungong
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //exchange 包含request和response
        log.info("----------------------经过了非法字符过滤器----------------------");
        //获取所有请求参数的值
        //获取request对象
        ServerHttpRequest request = exchange.getRequest();
        //获取response对象
        ServerHttpResponse response = exchange.getResponse();
        //使用request对象获取所有请求参数
        MultiValueMap<String, String> queryParamsMap = request.getQueryParams();
        //分割非法字符
        String[] illegalCharArray = illegalChar.split(",");
        //判断是否为null
        if(!CollectionUtils.isEmpty(queryParamsMap)){
            //http://localhost:18366/order/queryById?id=1&aa=11&bb=22&cc=33&dd=44&ee=['111','222','333']
            //循环遍历
            for (Map.Entry<String, List<String>> stringListEntry : queryParamsMap.entrySet()) {
                String paramValue = stringListEntry.getValue().get(0).toLowerCase();
                log.info("当前请求参数key为："+stringListEntry.getKey()); //第1次id  第2次aa  第3次bb...
                log.info("当前请求参数value为："+paramValue);//第1次1  第2次11  第3次22...

                //循环非法字符数组
                for (String illegalChar : illegalCharArray) {
                    //判断值是否合法
                    if(paramValue.contains(illegalChar)){
                        // 不合法则返回错误信息
                        Result result =new Result(ResultStatus.ILLEGAL_CHAR.getReturnCode(),
                                ResultStatus.ILLEGAL_CHAR.getReturnMessage(),"非法字符错误！！！！！！！！");

                        try {
                            byte[] datas = JSON.toJSONString(result).getBytes("utf-8");
                            DataBuffer buffer = response.bufferFactory().wrap(datas);
                            //添加响应头
                            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                            //写入自定义错误信息，并返回
                            return response.writeWith(Mono.just(buffer));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
        //chain.filter(exchange) 让程序继续运行
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 500;
    }
}
